<template>
  <div class="order-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>订单详情 - {{ orderData.orderNo }}</span>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loading">
        <!-- 基本信息 -->
        <el-col :span="16">
          <el-card class="info-card">
            <template #header>
              <span>订单信息</span>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{ orderData.orderNo }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :type="getStatusType(orderData.status)">
                  {{ getStatusText(orderData.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="客户姓名">{{ orderData.customerName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ orderData.customerPhone }}</el-descriptions-item>
              <el-descriptions-item label="服务类型">
                <el-tag>{{ getServiceTypeText(orderData.serviceType) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="订单金额">
                <span class="amount">¥{{ (orderData.amount || 0).toFixed(2) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="下单时间">{{ orderData.createTime }}</el-descriptions-item>
              <el-descriptions-item label="预期完成">{{ orderData.expectedTime }}</el-descriptions-item>
              <el-descriptions-item label="负责人">{{ orderData.worker || '未分配' }}</el-descriptions-item>
              <el-descriptions-item label="紧急程度">
                <el-tag :type="getUrgencyType(orderData.urgency)">
                  {{ getUrgencyText(orderData.urgency) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="取送地址" :span="2">{{ orderData.address }}</el-descriptions-item>
              <el-descriptions-item label="特殊要求" :span="2">{{ orderData.specialRequirements || '无' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 衣物清单 -->
          <el-card class="items-card">
            <template #header>
              <span>衣物清单</span>
            </template>
            <el-table :data="orderData.items || []" border>
              <el-table-column prop="name" label="衣物名称" />
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column prop="price" label="单价" width="100">
                <template #default="{ row }">
                  ¥{{ (row.price || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="小计" width="100">
                <template #default="{ row }">
                  ¥{{ ((row.quantity || 0) * (row.price || 0)).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="note" label="备注" />
            </el-table>
          </el-card>

          <!-- 订单日志 -->
          <el-card class="log-card">
            <template #header>
              <span>订单日志</span>
            </template>
            <el-timeline>
              <el-timeline-item
                v-for="(log, index) in orderLogs"
                :key="index"
                :timestamp="log.time"
                :type="log.type"
              >
                <div class="log-content">
                  <div class="log-title">{{ log.title }}</div>
                  <div class="log-description">{{ log.description }}</div>
                  <div class="log-operator">操作人：{{ log.operator }}</div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-col>

        <!-- 操作面板 -->
        <el-col :span="8">
          <el-card class="action-card">
            <template #header>
              <span>快速操作</span>
            </template>
            <div class="action-buttons">
              <el-button 
                type="primary" 
                @click="handleUpdateStatus"
                :disabled="!canUpdateStatus(orderData.status)"
                block
              >
                更新状态
              </el-button>
              <el-button 
                type="success" 
                @click="handleAssignWorker"
                block
              >
                分配工人
              </el-button>
              <el-button 
                type="warning" 
                @click="handleAddNote"
                block
              >
                添加备注
              </el-button>
              <el-button 
                type="info" 
                @click="handlePrint"
                block
              >
                打印订单
              </el-button>
            </div>
          </el-card>

          <!-- 进度追踪 -->
          <el-card class="progress-card">
            <template #header>
              <span>进度追踪</span>
            </template>
            <el-steps 
              :active="getProgressStep(orderData.status)" 
              direction="vertical"
              finish-status="success"
            >
              <el-step title="订单创建" description="客户下单" />
              <el-step title="订单确认" description="商家接单" />
              <el-step title="开始处理" description="进入洗护流程" />
              <el-step title="质量检查" description="质检确认" />
              <el-step title="等待取件" description="通知客户" />
              <el-step title="订单完成" description="客户确认" />
            </el-steps>
          </el-card>

          <!-- 客户信息 -->
          <el-card class="customer-card">
            <template #header>
              <span>客户信息</span>
            </template>
            <div class="customer-info">
              <div class="customer-item">
                <span class="label">姓名：</span>
                <span class="value">{{ orderData.customerName }}</span>
              </div>
              <div class="customer-item">
                <span class="label">电话：</span>
                <span class="value">{{ orderData.customerPhone }}</span>
              </div>
              <div class="customer-item">
                <span class="label">历史订单：</span>
                <span class="value">{{ customerStats.totalOrders || 0 }}单</span>
              </div>
              <div class="customer-item">
                <span class="label">累计消费：</span>
                <span class="value">¥{{ (customerStats.totalAmount || 0).toFixed(2) }}</span>
              </div>
              <el-button type="text" @click="handleViewCustomer">查看详情</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { order } from '@/api/wash/index'

const route = useRoute()
const loading = ref(false)

// 订单数据
const orderData = reactive({
  orderNo: '',
  status: '',
  customerName: '',
  customerPhone: '',
  serviceType: '',
  amount: 0,
  createTime: '',
  expectedTime: '',
  worker: '',
  urgency: 'normal',
  address: '',
  specialRequirements: '',
  items: []
})

// 订单日志
const orderLogs = ref([])

// 客户统计
const customerStats = reactive({
  totalOrders: 0,
  totalAmount: 0
})

// 获取订单详情
const getOrderDetail = async () => {
  loading.value = true
  try {
    const orderId = route.params.id
    
    // 调用真实API获取订单详情
    const response = await order.detail(orderId)

    if (response && response.data) {
      Object.assign(orderData, response.data)

      // 获取订单日志（如果API支持）
      if (response.data.logs) {
        orderLogs.value = response.data.logs
      } else {
        // 模拟订单日志
        orderLogs.value = [
          {
            time: orderData.createTime,
            type: 'primary',
            title: '订单创建',
            description: '客户下单成功',
            operator: '系统'
          }
        ]
      }

      // 获取客户统计（如果API支持）
      if (response.data.customerStats) {
        Object.assign(customerStats, response.data.customerStats)
      }
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 状态相关方法
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    accepted: 'primary',
    processing: 'primary',
    quality_check: 'info',
    ready: 'success',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待处理',
    accepted: '已接单',
    processing: '处理中',
    quality_check: '质检中',
    ready: '待取件',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

const getServiceTypeText = (type) => {
  const texts = {
    dry_clean: '干洗',
    water_wash: '水洗',
    ironing: '熨烫',
    repair: '修补',
    dyeing: '染色'
  }
  return texts[type] || '未知'
}

const getUrgencyType = (urgency) => {
  const types = {
    normal: '',
    urgent: 'warning',
    express: 'danger'
  }
  return types[urgency] || ''
}

const getUrgencyText = (urgency) => {
  const texts = {
    normal: '普通',
    urgent: '加急',
    express: '特急'
  }
  return texts[urgency] || '普通'
}

const getProgressStep = (status) => {
  const steps = {
    pending: 0,
    accepted: 1,
    processing: 2,
    quality_check: 3,
    ready: 4,
    completed: 5
  }
  return steps[status] || 0
}

const canUpdateStatus = (status) => {
  return !['completed', 'cancelled'].includes(status)
}

// 操作处理
const handleUpdateStatus = () => {
  ElMessage.info('状态更新功能开发中')
}

const handleAssignWorker = () => {
  ElMessage.info('工人分配功能开发中')
}

const handleAddNote = () => {
  ElMessage.info('添加备注功能开发中')
}

const handlePrint = () => {
  window.print()
}

const handleViewCustomer = () => {
  ElMessage.info('客户详情功能开发中')
}

// 生命周期
onMounted(() => {
  getOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail {
  padding: 20px;
  
  .detail-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .info-card, .items-card, .log-card {
    margin-bottom: 20px;
  }
  
  .amount {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
  }
  
  .action-card {
    margin-bottom: 20px;
    
    .action-buttons {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
  }
  
  .progress-card {
    margin-bottom: 20px;
  }
  
  .customer-card {
    .customer-info {
      .customer-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        
        .label {
          color: #666;
        }
        
        .value {
          font-weight: bold;
        }
      }
    }
  }
  
  .log-card {
    .log-content {
      .log-title {
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .log-description {
        color: #666;
        margin-bottom: 5px;
      }
      
      .log-operator {
        font-size: 12px;
        color: #999;
      }
    }
  }
}
</style> 